package com.leetcode.partition8;

/**
 * @author `RKC`
 * @date 2021/10/25 19:39
 */
public class LC712两个字符串的最小ASCII删除和 {

    public static int minimumDeleteSum(String s1, String s2) {
        return dynamicProgramming(s1, s2);
    }

    private static int dynamicProgramming(String s1, String s2) {
        //dp[i][j]：使s1[0, i]和s2[0, j]相等需要删除的最小ASCII码之和
        int[][] dp = new int[s1.length() + 1][s2.length() + 1];
        //初始状态，不管是s1还是s2，和空串相等就必修全部删除完
        for (int i = 1; i <= s1.length(); i++) dp[i][0] = dp[i - 1][0] + s1.charAt(i - 1);
        for (int j = 1; j <= s2.length(); j++) dp[0][j] = dp[0][j - 1] + s2.charAt(j - 1);
        for (int i = 1; i <= s1.length(); i++) {
            for (int j = 1; j <= s2.length(); j++) {
                if (s1.charAt(i - 1) == s2.charAt(j - 1)) {
                    //两个字符相等，不需要删除，直接使用之前的策略
                    dp[i][j] = dp[i - 1][j - 1];
                } else {
                    //字符不相等，要么删除s1[i]，要么删除s2[j]，要么同时删除
                    dp[i][j] = Math.min(Math.min(dp[i - 1][j] + s1.charAt(i - 1), dp[i][j - 1] + s2.charAt(j - 1)), dp[i - 1][j - 1] + s1.charAt(i - 1) + s2.charAt(j - 1));
                }
            }
        }
        return dp[s1.length()][s2.length()];
    }
}
